package org.jeecg.modules.car.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.car.CarInfo;
import org.jeecg.entity.car.CarOrder;
import org.jeecg.entity.car.CarPort;
import org.jeecg.entity.charge.ChargeInvoiceRequest;
import org.jeecg.entity.meter.MeterOrder;
import org.jeecg.enums.InvoiceTypeEnum;
import org.jeecg.enums.car.CarSyncStatusEnum;
import org.jeecg.modules.car.entity.CarFeeRule;
import org.jeecg.modules.car.entity.CarParkInfo;
import org.jeecg.modules.car.service.*;
import org.jeecg.modules.car.service.impl.ForeignCarJGSService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.service.IFeignChargeService;
import org.jeecg.vo.car.ForeignCarMonthlyRentReq;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

 /**
 * @Description: 车禁订单
 * @Author: liurui
 * @Date:   2020-09-16
 * @Version: V1.0
 */
@Slf4j
@Api(tags="车禁订单")
@RestController
@RequestMapping("/b/car/carOrder")
public class CarOrderController {
	@Autowired
	private ICarOrderService carOrderService;
	@Autowired
	private ICarFeeRuleService carFeeRuleService;
	@Autowired
	private ICarInfoService carInfoService;
	@Autowired
	private ICarParkInfoService carParkInfoService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;
	@Autowired
	private ForeignCarJGSService foreignCarJGSService;
	@Autowired
	private ICarPortService carPortService;
	 @Autowired
	 private IFeignChargeService feignChargeService;


	/**
	  * 分页列表查询
	 * @param carOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "车禁订单-分页列表查询")
	@ApiOperation(value="车禁订单-分页列表查询", notes="车禁订单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CarOrder>> queryPageList(CarOrder carOrder,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<CarOrder>> result = new Result<IPage<CarOrder>>();
		carOrder.setSqlMap(sysUserRoleService.dataScopeProjectOnlyFilter(SsoUtil.getLoginUser(),"p",carOrder.getMenuPath(),null,carOrder.getDepartIdEx()));
		Page<CarOrder> page = new Page<CarOrder>(pageNo, pageSize);
		List<CarOrder> list = carOrderService.findPage(page,carOrder);
		for (CarOrder resOrder:list){
			if (resOrder.getCarNo() != null && resOrder.getCarNo().length() > 10){
				resOrder.setCarNo("无牌车");
			}
		}
		page.setRecords(list);
		result.setSuccess(true);
		result.setResult(page);
		return result;
	}


	 @AutoLog(value = "车辆缴费订单--退款")
	 @ApiOperation(value="车辆缴费订单--退款", notes="车辆缴费订单--退款")
	 @GetMapping(value = "/refundCharge")
	 public Result refundCharge(@RequestParam(name = "orderId",required = true) String orderId){
		 return carOrderService.refundCharge(orderId);
	 }



	 @AutoLog(value = "获取费用详情")
	 @ApiOperation(value="费用详情", notes="费用详情")
	 @GetMapping(value = "/getFeeDetail")
	 public Result<CarOrder> getFeeDetail(@RequestParam(name = "months",required = true) Integer months,
										  @RequestParam(name = "carId",required = true) String carId,
										  @RequestParam(name = "feeStartDate",required = true) String feeStartDate,
										  @RequestParam(name = "carPortId",required = false) String carPortId){
		log.info("月租车续费获取费用详情接收参数:months={},carId={},feeStartDate={},carPortId={}",months,carId,feeStartDate,carPortId);
		CarInfo carInfo = carInfoService.getById(carId);
		 CarOrder carOrder = new CarOrder();
		 if (carInfo == null){
			 return Result.error("车辆在系统中不存在！");
		 }
		 if (months < 0){
			 return Result.error("充值月数不合规范！");
		 }
		 if (months > 24){
			 return Result.error("超过最大缴费月数！");
		 }
		 //固定车位
		 if (StringUtils.isNotBlank(carPortId)){
			 CarPort carPort = carPortService.getById(carPortId);
			 if (carPort == null){
				 return Result.error("未查询到此车固定车位信息！");
			 }
			 BigDecimal price = carPort.getPrice(); //单价
			//应缴金额
			 BigDecimal payDue = price.multiply(new BigDecimal(months));
			 carOrder.setPayAmount(payDue);
			 carOrder.setPayReduced(BigDecimal.ZERO);
			 carOrder.setPayDue(payDue);
		 }else {
			 CarFeeRule feeRule = carFeeRuleService.getById(carInfo.getFeeRuleId());
			 if (feeRule == null){
				 return Result.error("该车辆没有配置收费规则！");
			 }
			 if (months < feeRule.getLeastMonth()){
				 return Result.error("当前车辆月卡规则最低缴费为："+feeRule.getLeastMonth()+"个月");
			 }
			 int quo = 0;
			 if (feeRule.getBaseMonth() != null && feeRule.getBaseMonth() != 0){
				 quo = months/feeRule.getBaseMonth();   //商数
			 }
			//int remain = months%feeRule.getBaseMonth(); //余数
			 BigDecimal price = feeRule.getPrice(); //单价
			 int reducedMonth = 0;//优惠月数
			 if ( feeRule.getReducedMonth() != null ){
				 reducedMonth = feeRule.getReducedMonth();
			 }
			 //应缴金额
			 BigDecimal payDue = price.multiply(new BigDecimal(months));
			 //优惠金额
			 BigDecimal payReduced = BigDecimal.ZERO;
			 if (quo != 0){
				 payReduced = price.multiply(new BigDecimal(quo)).multiply(new BigDecimal(reducedMonth));
			 }
			 //实缴金额
			 BigDecimal payAmount = payDue.subtract(payReduced);
			 carOrder.setPayAmount(payAmount);
			 carOrder.setPayReduced(payReduced);
			 carOrder.setPayDue(payDue);
		 }
		 //费用涵盖日期
		 Calendar ca = Calendar.getInstance();
		 ca.setTime(DateUtils.str2Date(feeStartDate));
		 ca.add(Calendar.MONTH,months);
		 ca.add(Calendar.SECOND, -1);//减去1秒获取前一天
		 Date feeEndDate = ca.getTime();
		 carOrder.setCarId(carId);
		 carOrder.setCoverStartTime(DateUtils.str2Date(feeStartDate));
		 carOrder.setCoverEndTime(feeEndDate);
		 carOrder.setMonths(months);
		 return Result.ok(carOrder);
	 }


	 /**
	  * 下线充值
	  * @param carOrder
	  * @return
	  */
	 @RequestMapping({"unLineCharge"})
	 @ResponseBody
	 public Result unLineCharge(@RequestBody CarOrder carOrder){
	 	StringBuilder message = new StringBuilder();
	 	StringBuilder sb = new StringBuilder();
	 	Result<CarOrder> result;
	 	try{
			result = carOrderService.unLineCharge(carOrder);
		}catch (Exception e){
			log.error("月卡车下线续费异常:{}",e);
			return Result.error("续费异常,请联系管理员");
		}
		if (result.isSuccess()){
			 message.append("充值成功!");
		 	try {
		 		CarOrder carOrderCharge = result.getResult();
                CarInfo carInfo = carInfoService.getByCarId(carOrder.getCarId());
                	//AB车处理
                	if (StringUtils.isNotBlank(carInfo.getCarPortId())){
						List<CarInfo> infoList =  carInfoService.getByCarPortId(carInfo.getCarPortId());
						for (CarInfo info :infoList){
							CarInfo carPortInfo = carInfoService.getByCarId(info.getId());
							//已经同步车辆才添加车禁
							if (CarSyncStatusEnum.SYNC_STATUS_YES.getCode().equals(info.getSyncStatus()) && !carPortInfo.getLocalStartTime().equals(carPortInfo.getLocalEndTime())){
								CarParkInfo carParkInfo = carParkInfoService.getById(info.getParkId());
								ForeignCarMonthlyRentReq rentReq = new ForeignCarMonthlyRentReq();
								rentReq.setPark_id(carParkInfo.getOutSysId());
								rentReq.setCarmodelid(carPortInfo.getOutCarModel());
								rentReq.setCartypeid(carPortInfo.getOutCarType());
								rentReq.setPlate_number(carPortInfo.getCarNo());
								rentReq.setEmp_moblie(carOrderCharge.getUserMobile());
								rentReq.setEmp_name(carOrderCharge.getUserMobile());
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
								rentReq.setBegindate(sdf.format(carPortInfo.getLocalStartTime()));
								rentReq.setEnddate(sdf.format(carOrderCharge.getCoverEndTime()));
								Result rentResult = foreignCarJGSService.saveMonthlyRent(rentReq);
								if (rentResult.isSuccess()){
									sb.append(carPortInfo.getCarNo()+",");
									message.append(carPortInfo.getCarNo()+",同步线下车场成功!");
								} else {
									message.append(carPortInfo.getCarNo()+",同步下线车场失败！");
									log.error("同步线下车场失败信息",rentResult.getMessage());
								}
							}
						}
						//todo  ???
						carOrderService.updateSyncStatus(carOrderCharge.getId(), CarSyncStatusEnum.SYNC_STATUS_YES.getCode(),sb.toString());
                }else{
						//已经同步车辆才添加车禁
						if (CarSyncStatusEnum.SYNC_STATUS_YES.getCode().equals(carInfo.getSyncStatus())){
							CarParkInfo carParkInfo = carParkInfoService.getById(carInfo.getParkId());
							ForeignCarMonthlyRentReq rentReq = new ForeignCarMonthlyRentReq();
							rentReq.setPark_id(carParkInfo.getOutSysId());
							rentReq.setCarmodelid(carInfo.getOutCarModel());
							rentReq.setCartypeid(carInfo.getOutCarType());
							rentReq.setPlate_number(carInfo.getCarNo());
							rentReq.setEmp_moblie(carOrderCharge.getUserMobile());
							rentReq.setEmp_name(carOrderCharge.getUserMobile());
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							rentReq.setBegindate(sdf.format(carInfo.getLocalStartTime()));
							rentReq.setEnddate(sdf.format(carOrderCharge.getCoverEndTime()));
							Result rentResult = foreignCarJGSService.saveMonthlyRent(rentReq);
							if (rentResult.isSuccess()){
								message.append(carInfo.getCarNo()+",同步线下车场成功!");
								//更新订单同步状态
								carOrderService.updateSyncStatus(carOrderCharge.getId(), CarSyncStatusEnum.SYNC_STATUS_YES.getCode(), null);
							} else {
								message.append(carInfo.getCarNo()+",同步下线车场失败！");
								log.error("同步线下车场失败信息",rentResult.getMessage());
							}
						}else {
							carOrderService.updateSyncStatus(carOrderCharge.getId(), CarSyncStatusEnum.SYNC_STATUS_YES.getCode(), null);
						}
					}
			}catch (Exception e){
		 		log.error("车辆线下充值，同步下线车场异常",e);
				message.append(",同步下线车场异常！");
			}
             //TODO 开发票
            return Result.ok(message);
	 	} else {
	 		return  result;
	 	}
	 }

	 /**
	  *   扫码枪
	  * @param carOrder
	  * @return
	  */
	 @AutoLog(value = "月卡订单表-扫码枪充值")
	 @ApiOperation(value="月卡订单表-扫码枪充值", notes="月卡单表-扫码枪充值")
	 @RequestMapping({"unLineQRCodeCharge"})
	 @ResponseBody
	 public Result<MeterOrder> unLineQRCodeCharge(@RequestBody CarOrder carOrder) {
		 Result<MeterOrder> result = null;
		 try {
			 result = carOrderService.unLineQRCodeCharge(carOrder);
			 return result;
		 }catch (Exception ex){
			 return Result.error("系统繁忙，充值失败！");
		 }
	 }

	 @AutoLog(value = "月卡充值发票")
	 @ApiOperation(value="月卡充值发票", notes="月卡充值发票")
	 @RequestMapping(value = "/getInvoiceList")
	 public Result<List<ChargeInvoiceRequest>> getInvoiceList(@RequestParam(name = "orderNum", required = true) String orderNum){
		 try {
			 List<ChargeInvoiceRequest> list = carOrderService.invoiceRequestListBySn(orderNum);
			 return Result.ok(list);
		 }catch (Exception ex){
			 log.error("操作失败", ex.getMessage());
			 return Result.error("操作失败！");
		 }
	 }

	 @AutoLog(value = "发票红冲")
	 @ApiOperation(value="发票红冲", notes="发票红冲")
	 @RequestMapping(value = "/redInvoice")
	 public Result redInvoice(@RequestParam(name = "lsh", required = true) String lsh){
		 try {
			 ChargeInvoiceRequest req = carOrderService.invoiceRequestByFpqqlsh(lsh);
			 boolean b = feignChargeService.openRed(JSON.toJSONString(req), req.getTenantId());
			 if (b){
				 return Result.ok("红冲成功");
			 }
			 return Result.ok("红冲失败");
		 }catch (Exception ex) {
			 log.error("操作失败", ex.getMessage());
			 return Result.error("红冲失败！");
		 }
	 }

	 @AutoLog(value = "发票补开")
	 @ApiOperation(value="发票补开", notes="发票补开")
	 @RequestMapping(value = "/blueInvoice")
	 public Result blueInvoice(@RequestBody CarOrder carOrder){
		 try {
			 CarOrder order = carOrderService.getOrderBySn(carOrder.getSn());
			 if (order == null) return Result.error("订单在系统中不存在!");
			 boolean isOpenBlue = feignChargeService.isOpenBlue(carOrder.getSn(),order.getTenantId());
			 if (isOpenBlue) return Result.error("当前订单已开票,请勿重复开票!");
			 CarInfo carInfo = carInfoService.getByCarId(order.getCarId());
			 order.setFeeItemId(carInfo.getFeeitemId());
			 order.setInvoiceStatus(Integer.valueOf(InvoiceTypeEnum.INVOICE_TYPE_ELE.getCode()));
			 order.setInvoiceName(carOrder.getInvoiceName());
			 order.setInvoiceEmail(carOrder.getInvoiceEmail());
			 order.setInvoiceEin(carOrder.getInvoiceEin());
			 return carOrderService.carBlueInvoice(order);
		 }catch (Exception ex) {
			 log.error("操作失败:{}", ex);
			 return Result.error("补开失败！");
		 }
	 }

	 @ApiOperation(value = "查询付费通订单支付状态")
	 @GetMapping(value = "/checkOrderByTransNo")
	 public Result<Object> checkOrderByTransNo(@RequestParam(name="parkId",required=true) String parkId,
											   @RequestParam(name="transNo",required=true) String transNo){
		 Result<Object> result = null;
		 try {
			 result = carOrderService.checkOrderByTransNo(parkId, transNo);
		 }catch (Exception ex){
			 return Result.error("订单查询异常！");
		 }
		 return result;
	 }

	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "车禁订单-通过id查询")
	@ApiOperation(value="车禁订单-通过id查询", notes="车禁订单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CarOrder> queryById(@RequestParam(name="id",required=true) String id) {
		Result<CarOrder> result = new Result<CarOrder>();
		CarOrder carOrder = carOrderService.getById(id);
		if(carOrder==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(carOrder);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(CarOrder carOrder,HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
	  LoginUser user = SsoUtil.getLoginUser();
      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<CarOrder> pageList =  carOrderService.findPage(null,carOrder);
	  for (CarOrder resOrder:pageList){
		  if (carOrder.getCarNo() != null && carOrder.getCarNo().length() > 10){
			  carOrder.setCarNo("无牌车");
		  }
	  }
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "车辆订单明细");
      mv.addObject(NormalExcelConstants.CLASS, CarOrder.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("车辆订单明细数据", "导出人:" + user.getRealname(), "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<CarOrder> listCarOrders = ExcelImportUtil.importExcel(file.getInputStream(), CarOrder.class, params);
              carOrderService.saveBatch(listCarOrders);
              return Result.ok("文件导入成功！数据行数:" + listCarOrders.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
